import Taro, { Component } from "@tarojs/taro";
import { View, Input, Text, Image } from "@tarojs/components";
import {
  AtModal,
} from "taro-ui";
import { getToken } from "../../actions/account";
import "./verification.less";

class Verification extends Component {
  state = {
    liked: true,
    count: 60,
    timetemp: new Date().getTime()
  };

  sendVerificationCode() {
    if (this.props.status === 0) {
        this.props.parent.showModal()
    } else {
      this.vCodeForLoginOrRegister();
    }
  }

  async vCodeForLoginOrRegister() {
    if (!this.state.liked) {
      return;
    }
    const { parent } = this.props;
    const { status, tel } = parent.state;
    if (!tel && tel === "") {
      Taro.showToast({
        title: '手机号码不能为空。',
        icon: 'none',
        duration:2000
      })
      return false;
    }
    let vcode;
    if (parent.props.parent && parent.props.parent.state) {
      const { imgcode } = parent.props.parent.state
      vcode = imgcode;
    }
    let result = await getToken({ tel,status,vcode });
    if (result.state === "000") {
      this.setState({
        liked: false
      });
      const timer = setInterval(() => {
        this.setState(
          {
            count: this.state.count - 1
          },
          () => {
            if (this.state.count === 0) {
              clearInterval(timer);
              this.setState({
                liked: true,
                count: 60
              });
            }
          }
        );
      }, 1000);
    }
  }

  render() {
    const { liked, count } = this.state;
    return ([
      <Text
        onClick={this.sendVerificationCode.bind(this)}
        style="font-size:14px;color:#FAA24B;"
      >
        {liked ? "获取验证码" : count + "s"}
      </Text>,
    ]);
  }
}
export default Verification;
